package com.ykt.service;

import com.ykt.common.constant.ParamNames;
import com.ykt.common.utils.LonLatUtil;
import com.ykt.common.utils.UB;
import com.ykt.model.Market;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author wing
 * @version 1.0.0
 */
public class MarketService {

	private Market marketDao = Market.dao;


    public Market findByDistance(double lon, double lat){
        return findAll(lon, lat).get(0);
    }


    public List<Market> findAll(double lon, double lat){
        List<Market> markets = marketDao.findAll();
        
        // 默认查询ID为1的市场
        if(markets == null || markets.isEmpty()){
            return Arrays.asList(marketDao.findById(1));
        }

        // 默认查询ID为1的市场
        if(lon == 0 && lat == 0){
            return markets;
        }

        // 排序
        Map<Double, Market> map = new TreeMap<>(new Comparator<Double>() {
            @Override
            public int compare(Double o1, Double o2) {
                return o1 > o2 ? 1:0;
            }
        });

        double lon1 = lon;
        double lat1 = lat;

        for (Market market : markets) {
            double lon2 = UB.d(market.get(Market.longitude), -1);
            double lat2 = UB.d(market.get(Market.latitude), -1);
            if(lon2 == lat2 && lat2 == -1){
                continue;
            }

            double d = LonLatUtil.getDistance(lat1, lon1, lat2, lon2);
            map.put(d, market);
        }

        if(map.size() > 0){
            for (Map.Entry<Double, Market> entry : map.entrySet()) {
                entry.getValue().put(ParamNames.distance, entry.getKey()); // 返回最近距离的一个市场
            }
        }

        return new ArrayList<>(map.values()); // 返回排序后的市场，目前市场不多，全量暂时无性能问题。
    }


}
